<template>
  <div class="login-page">
    <img class="banner" src="//img.dmallcdn.com//dshop/201912/13b7b397-1d7b-4fda-80df-1c4030410765" />
    <bw-form ref="form" :mode="loginForm" :rule="loginRule">
      <bw-form-item>
        <div class="get-code-wrap">
          <bw-input
            v-model="loginForm.phone"
            placeholder="请输入手机号"
            type="phone"
          />
          <bw-button
            :disabled="disabled"
            type="primary"
            round
            inline
            plain
            class="get-code-btn"
            @click="getMsgCode"
          >
            <template v-if="time === 0">
              获取验证码
            </template>
            <template v-else>
              {{ time }}秒后重新获取
            </template>
          </bw-button>
        </div>
      </bw-form-item>
      <bw-form-item>
        <bw-input
          v-model="loginForm.code"
          placeholder="请输入验证码"
        />
      </bw-form-item>
    </bw-form>
    <bw-button
      type="primary"
      round
      @click="submit"
    >
      登录
    </bw-button>
  </div>
</template>

<script>
export default {
  name: 'Login',
  data () {
    return {
      loginForm: {
        phone: '',
        code: ''
      },
      loginRule: {
        phone: [
          { required: true, message: '请输入手机号'},
          { reg: /\d{11}/, message: '请输入正确格式手机号'}
        ],
        code: [
          { required: true, message: '请输入验证码' },
          { min: 6, max: 6, message: '请输入6为验证码' }
        ],
      },
      time: 0
    }
  },
  computed: {
    disabled () {
      return this.loginForm.phone.length !== 11 || this.time !== 0
    }
  },
  methods: {
    submit () {
      this.$refs.form.validate().then(() => {
        this.$store.dispatch('user/login', this.loginForm).then((res) => {
          this.$router.replace(this.$route.query.callbackUrl || '/home')
        })
      })
    },
    getMsgCode () {
      this.time = 10
      const interval = setInterval(() => {
        this.time -= 1
        if (this.time === 0) {
          clearInterval(interval)
        }
      }, 1000)
      this.$api.user.messageCode({
        phone: this.loginForm.phone
      }).then((res) => {
        console.log(res)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.login-page {
  .banner {
    display: block;
    width: 100%;
  }
  .get-code-wrap {
    @include wh(100%, 100px);
    @include flex(row, center, center);
    .get-code-btn {
      line-height: 1;
      font-size: 24px;
      flex-shrink: 0;
      margin-right: 20px;
    }
  }
  .submit-btn {
    width: calc(100% - 40px);
    display: block;
    margin: 0 20px;
  }
}
</style>
